package com.innova_t.android.Jordi;

import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

public class CallingActivity extends Activity {
String nombre;
RadioGroup rg;
ImageButton callin;
ImageButton callout;
Context mContext;
ArrayList<String> telefonos = null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.call_layout);
		mContext=getApplicationContext(); 
		Bundle extras = getIntent().getExtras();	
		if(extras != null){
			nombre = extras.getString("Nombre");
			telefonos = extras.getStringArrayList("listaTelefonos");
			TextView lblNombre = (TextView)findViewById(R.id.lblNombre);
			
			rg = (RadioGroup)findViewById(R.id.grupoTelefonos);
			callin = (ImageButton)findViewById(R.id.callin);
			callout = (ImageButton)findViewById(R.id.callout);
			
			callin.setOnClickListener(new View.OnClickListener() {
	             public void onClick(View v) {
	            	 Calling();
	             }
	         });
			
			callout.setOnClickListener(new View.OnClickListener() {
	             public void onClick(View v) {
	            	 HangUp();
	             }
	         });
			
			lblNombre.setText(nombre);
			createRadioButton();
		}		
	}

	private void createRadioButton() {
		int i=0;
		final RadioButton[] rb = new RadioButton[telefonos.size()];
        for (String telefono : telefonos) {
        	rb[i] = new RadioButton(this);
        	rb[i].setText(telefono.toString());
        	rb[i].setId(i);
            rg.addView(rb[i]);
            i++;
        }
        rb[0].setChecked(true);
	}
	
	private void Calling(){
		int index = rg.getCheckedRadioButtonId();
		int id = getResources().getIdentifier(String.valueOf(index), "id", mContext.getPackageName());
		RadioButton rd = (RadioButton)findViewById(id);
		
		Uri parsedPhoneNumber = Uri.parse("tel:" + rd.getText());
		Intent i = new Intent(Intent.ACTION_CALL,parsedPhoneNumber);
		startActivity(i); 	
	}
	
	private void HangUp(){
		    try{
		        this.finish();
		    }catch(Exception ex){
		        ex.printStackTrace();
		    }
	}
	
}
